package org.example.service;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.exception.CusAuthenticationException;
import org.example.mapper.UserMapper;
import org.example.model.vo.LoginUser;
import org.example.result.R;
import org.example.util.JwtUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;

@Component
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {


    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;

    private final AuthenticationManager authenticationManager;
    @Override
    public R login(String username, String password) {


        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        log.info("登录用户：{}", username);
        if (authenticate == null) {
            log.error("登录失败");
            return R.error().setMessage("用户名或密码错误");
        }
        Object principal = authenticate.getPrincipal();
        LoginUser loginUser = (LoginUser) principal;
        log.info("登录成功，用户信息：{}", loginUser);


        String tokenStr = JwtUtil.createJWT(JSONUtil.toJsonStr(loginUser));
        String tokenKey = "token:" + tokenStr;
        stringRedisTemplate.opsForValue().set(tokenKey, tokenStr, Duration.ofMillis(JwtUtil.JWT_TTL));
        return R.ok().setData(Collections.singletonMap("token", tokenStr));
    }

    @Override
    public R logout(HttpServletRequest request) throws CusAuthenticationException {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            String tokenKey = "token:" + token;
            stringRedisTemplate.delete(tokenKey);
            return R.ok();
        }
        throw new CusAuthenticationException("token 为空");
    }
}
